package com.carcenter.sms.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.carcenter.common.dto.SmsDto;
import com.carcenter.sms.config.SmsTemplate;
import com.carcenter.sms.service.SmsService;
import com.carcenter.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * @author yellow Doctor
 * @date 2025-06-24
 * @desc 蜗牛创想：www.woniuxy.com
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private SmsTemplate smsTemplate;

    //发送短信

    @Override
    public Result sendCode(String mobile) {

        String lockKey = "lockKey:" + mobile;
        // 检查账号是否被锁定
        String lock = stringRedisTemplate.opsForValue().get(lockKey);
        if (StringUtils.hasText(lock)) {
            return Result.ok("账号已经锁定，请联系管理员解锁");
        }

        // 计数和锁定的键
        String countKey = "count:" + mobile;
        // 01 随机生成验证码
        String code = RandomUtil.randomNumbers(6);
        log.info("当前生成的手机号验证码是："+code);

        //检查已经发送验证码次数
        String count = stringRedisTemplate.opsForValue().get(countKey);
        if (count == null || count == "") {
            count = "0";
            stringRedisTemplate.opsForValue().set(countKey, count, Duration.ofMinutes(5));
        }

//        // 验证码还没有过期，直接返回
        String redisKey = "user:code:" + mobile;
        if (stringRedisTemplate.hasKey(redisKey)) {
            return Result.ok("验证码尚未过期，请稍后再试");
        }

        // 检查是否超过发送次数限制
        if (Integer.parseInt(count) <= 3) {
            // 存储验证码到Redis
            stringRedisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));
            // 发送次数自增
            stringRedisTemplate.opsForValue().increment(countKey);
            SmsDto smsDto = new SmsDto();
            smsDto.setMobile(mobile);
            smsDto.setCode(code);
            // mq调用短信模板发送短信
            rabbitTemplate.convertAndSend("tel.queue", smsDto);
            return Result.ok("验证码发送成功");
        } else {
            // 超过次数限制，锁定账号
            stringRedisTemplate.opsForValue().set(lockKey, "lock", Duration.ofHours(2));
            return Result.ok("频繁发送短信，账号被锁2小时");
        }
    }


}
